package com.lbs.until;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Administrator
 * @date 2021/5/17 9:45
 * @description
 **/
public class BaseDaoUntil<T> {

    QueryRunner runner = new QueryRunner();

    // 通用增删改
    public int update(String sql, Object...param){
        Connection connection = null;
        JdbcUntil jdbcUntil = null;
        try {
            jdbcUntil = JdbcUntil.getInstance();
            connection = jdbcUntil.getConnection();
            return runner.update(connection,sql,param);
        } catch (SQLException e) {
            throw new RuntimeException("操作失败!"+e);
        } finally {
            jdbcUntil.CloseAll(connection);
        }
    }

    public T findOne(String sql, Class cls, Object...param) {
        Connection connection = null;
        JdbcUntil jdbcUntil = null;
        try {
            jdbcUntil = JdbcUntil.getInstance();
            connection = jdbcUntil.getConnection();
            return runner.query(connection, sql, new BeanHandler<T>(cls), param);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询失败！" + e);
        } finally {
            jdbcUntil.CloseAll(connection);
        }
    }

    public List<T> findMore(String sql, Class cls, Object...param) {
        Connection connection = null;
        JdbcUntil jdbcUntil = null;
        try {
            jdbcUntil = JdbcUntil.getInstance();
            connection = jdbcUntil.getConnection();
            return runner.query(connection, sql, new BeanListHandler<T>(cls), param);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("查询失败！" + e);
        } finally {
            jdbcUntil.CloseAll(connection);
        }
    }

}
